import React, { Component } from "react";
// import ReactDom from "react-dom"
import "./Login.css";
import "bootstrap/dist/css/bootstrap.css";
import axios from "axios";
import { NavLink } from "react-router-dom";
import { notification } from "antd";
import cookie from 'react-cookies';

class Login extends Component {
  state = {
    verifyCode: "",
    inputVerifyCode: "",
    countDown: 10,
    isGetBtn: true,
    Email: "",
    Pwd: "",
    inToken: ""
  };

  componentWillUnmount = () => {
    clearInterval(this.state.inToken)
  }
  //获取验证码方法
  getVerify = () => {
    let { countDown, isGetBtn, Email } = this.state;
    if (!isGetBtn) return;

    var reg = /@+[a-zA-z]+(.com)+/;
    if (!reg.test(Email)) {
      notification['warning']({
        message: '邮箱格式不正确',
        description: '请检查邮箱输入'
      })
      return;
    }

    axios.get(`http://localhost:5500/ant/ant/Login/GetVerify?Email=${Email}`).then(
      (response) => {
        console.log(response.data);
        this.setState({ verifyCode: response.data });
      })
      .catch(err => console.log(err));

    this.setState({ isGetBtn: false });

    ///进入倒计时
    var iID = setInterval(() => {
      if (this.state.countDown === 0) {
        this.setState({ isGetBtn: true });
        this.setState({ countDown: 10 });
        clearInterval(iID);
      } else this.setState({ countDown: countDown-- });
    }, 1000);
    this.setState({ inToken: iID });
  };

  actionLogin = (event) => {
    event.preventDefault();
    let { verifyCode, Pwd, inputVerifyCode, Email } = this.state;

    if (Pwd === "") {
      notification['warning']({
        message: '密码不能为空',
        description: '请检查密码输入'
      })
      return;
    }
    if (
      !(inputVerifyCode !== "" && inputVerifyCode === verifyCode.toString())
    ) {
      notification['warning']({
        message: '验证码错误',
        description: '请检查验证码输入'
      })
      return;
    }
    var data = { "Email": Email, "Pwd": Pwd }
    axios
      .post("http://localhost:5500/ant/ant/Login/Index", data)
      .then((response) => {
        if (response.status === 200) {
          axios.defaults.headers.common['Authorization'] = 'bearer ' + response.data.token
          cookie.save('userID', response.data.userID)
          cookie.save('userEmail', response.data.userEmail)
          cookie.save('userName', response.data.userName)
          cookie.save('userRole', response.data.userRole)
          cookie.save('userStore', response.data.userStore)
          notification['success']({
            message: '登陆成功',
            description: '3s秒钟后自动跳转'
          })
          let url = "/cashier/create"
          if (response.data.userStore === -1) {
            url = "/join"
          }
          setTimeout(() => {
            this.props.history.replace(url)
          }, 3000);
        }
      }, err => {
        console.log(err);
      })
      .catch(function (error) {
        console.log(error);
        notification['warning']({
          message: '登陆失败',
          description: '账号或密码错误'
        })
      });
  };

  render() {
    return (
      <div>
        <br />
        <br />
        <br />
        <div id="login-center-box">
          <form
            id="login-from"
            onSubmit={(event) => this.actionLogin(event)}
            ref={(form1) => (this.form1 = form1)}
          >
            <br />
            <label htmlFor="login-from" style={{ fontSize: "30px" }}>
              登录
            </label>
            <br />
            <br />
            <div className="form-group">
              <label htmlFor="emailHelp">账号(邮箱)</label>
              <input
                type="email"
                className="form-control"
                name="Email"
                id="account"
                aria-describedby="emailHelp"
                onChange={(input) =>
                  this.setState({ Email: input.target.value })
                }
              />
              {/*  console.log(input.target.value) */}
            </div>
            <br />
            <div className="form-group">
              <label htmlFor="InputPassword">密码</label>
              <input
                type="password"
                className="form-control"
                name="Pwd"
                id="InputPassword"
                onChange={(input) => this.setState({ Pwd: input.target.value })}
              />
            </div>
            <br />
            <div className="form-group">
              <label htmlFor="Verify">验证码</label>
              <div className="input-group mb-3">
                <input
                  type="text"
                  id="Verify"
                  className="form-control"
                  placeholder="验证码"
                  aria-label="验证码"
                  aria-describedby="button-addon2"
                  onChange={(input) =>
                    this.setState({ inputVerifyCode: input.target.value })
                  }
                />
                <div className="input-group-append">
                  <button
                    className="btn btn-outline-secondary"
                    ref={(btn) => (this.GetVerifyBtn = btn)}
                    onClick={this.getVerify}
                    type="button"
                    id="button-addon2"
                  >
                    {!this.state.isGetBtn
                      ? `${this.state.countDown}秒后重试`
                      : "获取验证码"}
                  </button>
                </div>
              </div>
            </div>
            <br />
            <div className="from-group row">
              <div className="col-4 offset-8">
                <NavLink className="text-center" to="/register">
                  注册账号
                </NavLink>
              </div>
            </div>
            <div className="from-group">
              <input
                type="submit"
                className="btn bg-danger text-white"
                style={{ width: "100%", fontSize: "20px" }}
                value="登录"
              />
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default Login;
